package com.mesSystem.service.impl.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mesSystem.entity.ProcessWorkstation;
import com.mesSystem.entity.Workstation;
import com.mesSystem.entity.WorkstationAndEmployee;
import com.mesSystem.mapper.ProcessWorkstationMapper;
import com.mesSystem.service.impl.PadManagementService;
import com.mesSystem.service.impl.ProcessService;
import com.mesSystem.service.impl.ProcessWorkstationService;
import com.mesSystem.service.impl.WorkstationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class ProcessWorkstationServiceImpl extends ServiceImpl<ProcessWorkstationMapper, ProcessWorkstation> implements ProcessWorkstationService {

    /**
     * 更新工位信息，通过标记在前端标记工位状态，完成工位信息的增删
     * @param workstationIds
     * @param processName
     */
    public void update(List<Long> workstationIds, String processName) {
        // 创建一个对象用来对比数据库信息
        ProcessWorkstation processWorkstation = new ProcessWorkstation();
        processWorkstation.setProcessName(processName);
        for (Long workstationId : workstationIds) {
            processWorkstation.setWorkstationId(workstationId);
            // 如果工位id已存在，则删除
            if (count(new QueryWrapper<>(processWorkstation)) > 0) {
                remove(new QueryWrapper<>(processWorkstation));
            } else {
                // 如果未存在，则添加新的工位id
                save(processWorkstation);
            }
        }
    }
    @Autowired
    WorkstationService workstationService;

    /**
     * 根据工序名称查询工序中工位的信息
     * @param page
     * @param size
     * @param processName
     */
    @Override
    public List<Workstation> queryByProcessName(Integer page, Integer size, String processName) {
        // 创建分页对象
        Page<ProcessWorkstation> pages = new Page<>(page, size);
        // 创建查询对象，根据processName查询
        QueryWrapper<ProcessWorkstation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("process_name",processName);

        // 调用分页查询方法，将分页器和查询条件传递给 service
        page(pages, queryWrapper);

        // 从分页器对象中获取分页后的数据
        List<ProcessWorkstation> processWorkstations = pages.getRecords();

        // 提取设备ID和姓名并返回
        List<Workstation> workstations = processWorkstations.stream()
                .map(processWorkstation -> {
                    Long workstationId = processWorkstation.getWorkstationId();
                    String workstationName = workstationService.getWorkstationName(workstationId);
                    return new Workstation(workstationId, workstationName);
                })
                .collect(Collectors.toList());
        return workstations;
    }

}
